<!-- eslint-disable no-unused-vars -->
<template>
  <el-card class="card">
    <div class="app-container">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            :size="$elementSize.value"
            >新增节点</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            :size="$elementSize.value"
            type="info"
            plain
            icon="Sort"
            @click="toggleExpandAll"
            >展开/折叠</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="getConfigs"
            :size="$elementSize.value"
            >刷新</el-button
          >
        </el-col>
      </el-row>

      <el-table
        v-if="refreshTable"
        v-loading="loading"
        :data="filteredListData"
        row-key="key"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column
          prop="name"
          label="名称"
          :show-overflow-tooltip="true"
          width="200"
        ></el-table-column>
        <el-table-column prop="value" label="值" align="center">
          <template #default="scope">
            <span v-if="scope.row.name == 'password'">********</span>
            <span v-else>{{ scope.row.value }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          align="left"
          width="210"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-if="!notUpdateList.includes(scope.row.name) "
              >修改</el-button
            >
            <el-button
              link
              type="primary"
              icon="Plus"
              @click="handleAdd(scope.row)"
              v-if="!scope.row.value"
              >新增</el-button
            >
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-if="!notDeleteList.includes(scope.row.name)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加或修改菜单对话框 -->
      <el-dialog
        :title="title"
        v-model="open"
        width="680px"
        draggable
        append-to-body
      >
        <el-form ref="menuRef" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="路径：" prop="key">
                <el-input v-model="form.key" placeholder="" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="名称：" prop="name">
                <el-input v-model="form.name" :disabled="nameAble" />
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="title === '修改' && form.value">
              <el-form-item label="值：" prop="value">
                <el-input v-model="form.value" />
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="title === '添加'">
              <el-form-item>
                <el-switch
                  v-model="isNote"
                  class="mb-2"
                  active-value="1"
                  inactive-value="0"
                  active-text="键值对"
                  inactive-text="节点"
                  v-if="!form.value"
                />
              </el-form-item>
            </el-col>

            <el-col :span="24" v-if="title == '添加'">
              <el-form-item label="新名称：" prop="newName">
                <el-input v-model="form.newName" />
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="title == '添加' && isNote == 1">
              <el-form-item label="新值：" prop="newValue">
                <el-input v-model="form.newValue" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button
              :size="$elementSize.value"
              type="primary"
              @click="submitForm"
              >确 定</el-button
            >
            <el-button :size="$elementSize.value" @click="cancel"
              >取 消</el-button
            >
          </div>
        </template>
      </el-dialog>
    </div>
  </el-card>
</template>

<script setup name="Menu">
import { deepCopy } from "@/utils/common.js";
import {
  ref,
  getCurrentInstance,
  reactive,
  toRefs,
  nextTick,
  onMounted,
  computed,
} from "vue";

const { proxy } = getCurrentInstance();

import { ElMessage, ElMessageBox } from "element-plus";
import { getConfig, updateConfig } from "@/api/user.js";
const open = ref(false);
const loading = ref(true);
const title = ref("");
const menuOptions = ref([]);
const isExpandAll = ref(false);
const refreshTable = ref(true);
const props = defineProps({
  send_data: {
    type: Array, // 对象类型
    default() {
      return []; //默认值
    },
  },
});
const isNote = ref(0);
const data = reactive({
  form: {},
  queryParams: {
    menuName: undefined,
    visible: undefined,
  },
  rules: {
    menuName: [
      { required: true, message: "菜单名称不能为空", trigger: "blur" },
    ],
    orderNum: [
      { required: true, message: "菜单顺序不能为空", trigger: "blur" },
    ],
    path: [{ required: true, message: "路由地址不能为空", trigger: "blur" }],
  },
});
// 不显示修改按钮
const notUpdateList = ['config', 'dingdingSend', 'button', 'client', 'admin']
// 不显示删除按钮
const notDeleteList = ['config', 'dingdingSend', 'button', 'client', 'admin','webhook', 'secret', 'appPath', 'appName','appLog', 'password', 'user', 'permission']
// 不可修改节点名称
const notUpdateNameList = ['webhook', 'secret', 'appPath', 'appName','appLog', 'user', 'permission']
const nameAble = computed(() => notUpdateNameList.includes(form.value.name))

const { form, rules } = toRefs(data);

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    key: "",
    name: "",
    value: "",
  };
}
// const emit = difineEmits(['get-message','update:msg'])
// function refresh() {

// }
const listData = ref([]);
// 计算属性，过滤掉 name 为 'password' 的行
const filteredListData = ref([]);

const getConfigs = async () => {
  loading.value = true;
  let res = await getConfig();
  if (res.data.code == 200) {
    let config = res.data.data;
    listData.value = deepCopy(config);
    filteredListData.value = deepCopy(config);
    // 递归过滤掉所有 name 为 'password' 的对象
    function filterPassword(arr) {
      return arr
        .filter((item) => item.name !== "password") // 过滤当前层级的 'password'
        .map((item) => {
          if (item.children && item.children.length > 0) {
            // 递归处理子项
            item.children = filterPassword(item.children);
          }
          return item;
        });
    }
    // 调用过滤函数
    filteredListData.value = filterPassword(filteredListData.value);
    ElMessage.success("获取配置成功");
  }
  loading.value = false;
};
/** 提交按钮 */
async function submitForm() {
  // 更新函数
  function updateListData(lists, updateData) {
    // 遍历 lists
    lists.forEach((item) => {
      // 如果当前项有 children，递归处理
      if (item.children && item.children.length > 0) {
        updateListData(item.children, updateData);
      }

      // 如果当前项的 key 匹配，更新对应的 name 和 value
      if (item.key === updateData.key) {
        item.name = updateData.name;
        item.value = updateData.value;
      }
    });
  }
  let msg = "";
  if (title.value == "修改") {
    updateListData(listData.value, form.value);
    msg = "修改成功";
  } else {
    if (form.value.key)
      form.value.newKey = `${form.value.key}-${form.value.newName}`;
    else form.value.newKey = form.value.newName;
    if (!form.value.newValue) {
      form.value.newValue = "";
    }
    // 递归函数，遍历所有 children
    function addNestedKey(list, updateData) {
      if (!updateData.key) {
        list.push({
          name: updateData.newName,
          value: "",
          key: updateData.newKey,
        });
        return;
      }
      list.forEach((item) => {
        // 如果当前项的 key 匹配，更新其值
        if (item.key === updateData.key) {
          // 子列表不存在新增列表
          if (!item.children) item.children = [];
          let status = true;
          // 查找子类里是否已存在新加项
          item.children.forEach((item2) => {
            if (item2.name == updateData.newName) {
              status= false;
            }
          });
          // 存在新加项不再新建
          if (status) {
            item.children.push({
              name: updateData.newName,
              value: updateData.newValue,
              key: updateData.newKey,
            });
          }
        }
        // 如果当前项有 children，递归更新子项
        if (item.children && item.children.length > 0) {
          addNestedKey(item.children, updateData);
        }
      });
    }
    addNestedKey(listData.value, form.value);
    msg = "添加成功";
  }
  let res = await updateConfig(listData.value);
  if (res.data.code == 200) {
    ElMessage.success(msg);
    getConfigs();
  } else ElMessage.error(res.data.msg);
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  form.value = deepCopy(row);
  open.value = true;
  title.value = "修改";
}
/** 新增按钮操作 */
function handleAdd(row) {
  if (row) form.value = deepCopy(row);
  else form.value["key"] = "";
  open.value = true;
  title.value = "添加";
}
/** 删除按钮操作 */
function handleDelete(row) {
  const key = row.key;
  let delList = deepCopy(listData.value);
  // 递归删除匹配key的对象
  function removeKeyFromList(list, updateData) {
    // 递归地删除匹配 key 的项
    return list.filter((item) => {
      // 如果当前项的 key 与 updateData.key 匹配，删除该项
      if (item.key === updateData.key) {
        return false; // 删除该项
      }

      // 如果有 children，递归删除
      if (item.children && item.children.length > 0) {
        // 递归调用删除子项
        item.children = removeKeyFromList(item.children, updateData);
      }

      // 保留其他项
      return true;
    });
  }
  ElMessageBox.confirm(
    '是否确认删除key为"' + key + '"的"' + row.name + '"配置?',
    "系统提示",
    {
      type: "warning",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
    }
  )
    .then(async function () {
      delList = delList.filter((item) => {
        if (item.key == row.key) {
          return false;
        }
        return true;
      });
      removeKeyFromList(delList, row);
      let res = await updateConfig(delList);
      if (res.data.code == 200) {
        ElMessage.success("修改成功");
        getConfigs();
      } else ElMessage.error(res.data.msg);
    })
    .catch(() => {});
}
/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 修改按钮操作 */
onMounted(() => {
  getConfigs();
});
</script>
